package com.hmdp.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class RedisIdWorker {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     *
     * @param KeyPrefix 业务前缀
     * @return
     */

    private static final long BEGIN_TIMESTAMP =1672531200L;
    private static final long COUNT_BITS =32;

    public long nextId(String KeyPrefix){
        //1、生成时间戳
        //1.2、当前时间减去 begin_timestamp
        LocalDateTime now = LocalDateTime.now();
        long nowSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp =nowSecond -BEGIN_TIMESTAMP;

        //2、生成序列号
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        Long count = stringRedisTemplate.opsForValue().increment("icr:" + KeyPrefix + ":" + date);


        //3、拼接
        //由于timestamp 是64为的long型数据 ，且此时只占了后面32位。
        //所以可以对timestamp，向左移动32位，再用 | 加上count。
        return timestamp << COUNT_BITS | count;
    }

    public static void main(String[] args) {
        LocalDateTime time = LocalDateTime.of(2023, 1, 1, 0, 0, 0);
        long l = time.toEpochSecond(ZoneOffset.UTC);
        System.out.println(l);
    }
}
